package com.powernode.customer.service.impl;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.customer.mapper.CustomerInfoMapper;
import com.powernode.customer.mapper.CustomerLoginLogMapper;
import com.powernode.customer.service.CustomerInfoService;
import com.powernode.model.entity.customer.CustomerInfo;
import com.powernode.model.entity.customer.CustomerLoginLog;
import com.powernode.model.form.customer.UpdateWxPhoneForm;
import com.powernode.model.vo.customer.CustomerLoginVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Resource
    private WxMaService wxMaService;

    @Resource
    private CustomerLoginLogMapper customerLoginLogMapper;

    /**
     * 顾客登录
     * 1.获取用户的微信openId
     * 2.根据微信openId查询用户信息
     * 3.若用户信息不存在，则插入用户信息
     *
     * @return 主键
     */
    @Transactional
    @Override
    public Long login(String code) {
        CustomerInfo customerInfo = null;
        try {
            //1.获取用户的微信openId
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            String openid = sessionInfo.getOpenid();

            //2.根据微信openId查询用户信息
            LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CustomerInfo::getWxOpenId, openid);//构建查询条件
            customerInfo = this.getOne(queryWrapper);

            //3.若用户信息不存在，则插入用户信息
            if (customerInfo == null) {
                //用户第一次来
                customerInfo = new CustomerInfo();
                customerInfo.setWxOpenId(openid);
                //头像
                customerInfo.setAvatarUrl("https://img.phb123.com/uploads/allimg/220805/810-220P51012170-L.png");
                //昵称
                customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));

                customerInfo.setCreateTime(new Date());

                this.save(customerInfo);
            }

            //记录登录日志
            CustomerLoginLog customerLoginLog = new CustomerLoginLog();
            customerLoginLog.setCustomerId(customerInfo.getId());
            customerLoginLog.setMsg("微信小程序登录");
            customerLoginLog.setCreateTime(new Date());

            customerLoginLogMapper.insert(customerLoginLog);

        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

        return customerInfo.getId();
    }


    /**
     * 获取顾客信息
     */
    @Override
    public CustomerLoginVo getCustomerLoginInfo(Long customerId){
        CustomerInfo customerInfo = getById(customerId);
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();

        BeanUtils.copyProperties(customerInfo, customerLoginVo);

        //是否绑定手机号码
        boolean isBindPhone = StringUtils.hasText(customerInfo.getPhone());

        customerLoginVo.setIsBindPhone(isBindPhone);

        return customerLoginVo;
    }


    /**
     * 获取用户手机号 存入数据库
     */
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {

        try {
            //获取用户手机号 给微信服务器发送请求，获取用户手机号
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
            String phoneNumber = phoneNoInfo.getPhoneNumber();

            CustomerInfo customerInfo = new CustomerInfo();
            customerInfo.setId(updateWxPhoneForm.getCustomerId());
            customerInfo.setPhone(phoneNumber);
            boolean flag = this.updateById(customerInfo);

            return flag;

        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }
}
